package com.example.weblending.exception;

import com.example.weblending.domain.File;
import com.example.weblending.domain.Task;
import com.example.weblending.service.FileService;
import com.example.weblending.service.TaskService;
import org.springframework.aop.interceptor.AsyncUncaughtExceptionHandler;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.lang.reflect.Method;
import java.sql.Timestamp;

@Component
public class CustomAsyncExceptionHandler implements AsyncUncaughtExceptionHandler {
    @Autowired
    private TaskService taskService;

    @Autowired
    private FileService fileService;

    private static CustomAsyncExceptionHandler testUtil;

    @PostConstruct
    public void init(){
        testUtil = this;
    }

    @Override
    public void handleUncaughtException(Throwable throwable, Method method, Object... objects) {
        for (Object param : objects) {
            System.out.println("Parameter value - " + param);
            if((param instanceof File)){
                File f=testUtil.fileService.getById(((File)param).getFid());
                Task task=testUtil.taskService.getById(f.getTask());
                task.setEndtime(new Timestamp(System.currentTimeMillis()));
                task.setState(-1);
                task.setDescption(throwable.getMessage());
                f.setTask(0);
                testUtil.fileService.updateById(f);
                testUtil.taskService.updateById(task);
            }
        }
    }
}